package com.huanglejing.shanggou.rx.oepration

import android.os.Bundle
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.rx.event.OnResultEvent
import com.huanglejing.shanggou.rx.rxbus.RxBus
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.UIHelper
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1

/**
 * Created by Administrator on 2016/9/21 0021.
 * 等待登录结果操作
 */
class LoginOperation<T>(private val tag: String/*特定标识符*/
                        , private val resultEventAction1: Action1<OnResultEvent.OnLoginResultEvent> //登录结果，data为boolen值
) : Func1<T, Observable<T>> {


    private fun getLoginObservable(data: T, resultEventAction1: Action1<OnResultEvent.OnLoginResultEvent>): Observable<T> {
        val bundle = Bundle()
        bundle.putString(C.BundleKey.KEY1, C.Constants.LOGIN_NEED_BACK)
        bundle.putString(C.BundleKey.KEY2, tag)
        //UIHelper.startActivity(LoginActivity::class.java, bundle)
        return RxBus.get().toObservable(OnResultEvent.OnLoginResultEvent::class.java)
                .filter { resultEvent -> tag == resultEvent.tag }
                .takeUntil { onLoginResultEvent -> !onLoginResultEvent.data }
                .observeOn(AndroidSchedulers.mainThread()).doOnNext(resultEventAction1)
                .filter { it.data }
                .map { data }

    }

    override fun call(t: T): Observable<T> {
        return try {
          //  if (! AppContext.account().isLogin /**/) {   //TODO
                //监听登陆返回
                getLoginObservable(t, resultEventAction1)
         //   } else {
                Observable.just(t)
        //    }
        } catch(e: Exception) {
            Observable.empty<T>()
        }
    }
}


